import React, { useEffect, useCallback, useState } from "react";
import type { ActionType, ProColumns, ProFormColumnsType } from "@ant-design/pro-components";
import PcForm from "../PcForm";
import PcTable from "../PcTable";
import type { FormInstance } from "antd";
import type { PcPageProps } from "./types";
import { debounce } from 'lodash';

interface ExtendedActionType<P> extends ActionType {
  onSearch: (values: P) => Promise<void>;
  onReset: () => void;
  onResetAndSearch: () => void;
}

/**
 * PC端页面组件的属性类型
 * @template T - 数据类型
 * @template P - 搜索参数类型
 */
export interface PcPageProps<T, P extends Record<string, any> = Partial<T>> {
  /** 列配置 */
  columns: ProColumns<T>[];
  /** 表格数据源 */
  dataSource: T[];
  /** 表格加载状态 */
  loading?: boolean;
  /** 表格行的key */
  rowKey: string;
  /** 表格的ref */
  actionRef?: React.MutableRefObject<ActionType | undefined>;
  /** 表单的ref */
  formRef?: React.MutableRefObject<FormInstance | undefined>;
  /** 可编辑的行key数组 */
  editableKeys: React.Key[];
  /** 设置可编辑行的回调 */
  setEditableRowKeys: (keys: React.Key[]) => void;
  /** 分页配置 */
  pagination: {
    total: number;
    pageSize: number;
    current: number;
    onChange: (current: number, pageSize: number) => void;
  };
  /** 新建记录的默认值 */
  createRecordTemplate?: () => T;
  /** 保存编辑的回调 */
  onSave?: (key: React.Key, row: T) => Promise<boolean>;
  /** 取消编辑的回调 */
  onCancel?: (key: React.Key) => void;
  /** 工具栏渲染函数 */
  toolBarRender?: () => React.ReactNode[];
  /** 页面操作引用 */
  pageRef: React.MutableRefObject<ExtendedActionType<P>>;
}

/**
 * PC端页面组件
 * @template T - 数据类型
 * @template P - 搜索参数类型
 */
const PcPage = <
  T extends Record<string, any>,
  P extends Record<string, any> = Partial<T>
>(
  props: PcPageProps<T, P>
) => {
  const {
    columns,
    dataSource,
    loading,
    rowKey,
    actionRef,
    formRef,
    pageRef,
    pagination,
    pageConfig,
    formConfig,
    onCancel,
    editable,
    toolBarRender,
  } = props;

  // 内部分页状态
  const [internalPagination, setInternalPagination] = useState({
    current: pagination.current,
    pageSize: pagination.pageSize,
  });

  // 获取搜索列配置
  const searchColumns = React.useMemo(() => {
    return columns
      .filter((column) => !column.hideInSearch)
      .map((column) => {
        const { formItemProps, ...rest } = column;
        return {
          ...rest,
          formItemProps: {
            ...formItemProps,
            rules: undefined,
          },
          readonly: undefined,
        };
      }) as ProFormColumnsType<P>[];
  }, [columns]);

  // 处理分页变化
  const handlePaginationChange = useCallback(
    debounce((current: number, pageSize: number) => {
      // 更新内部分页状态
      setInternalPagination({ current, pageSize });
      // 调用外部onChange
      if (pagination.onChange) {
        pagination.onChange(current, pageSize);
      }
      // 进行查询，直接使用传入的 current 和 pageSize
      const currentFormValues = formRef?.current?.getFieldsValue() || {};
      const { page, current: formCurrent, pageSize: formPageSize, ...restValues } = currentFormValues;
      
      // 进行查询，合并表单值和分页参数
      pageRef.current?.onSearch({
        ...restValues,
        current,
        pageSize,
      } as unknown as P);
    }, 300), // 300ms 防抖
    [pagination, pageRef, formRef]
  );

  return (
    <div>
      <PcForm<P>
        columns={searchColumns}
        onFinish={pageRef.current?.onSearch}
        onReset={pageRef.current?.onReset}
      />
      <PcTable<T>
        columns={columns}
        dataSource={dataSource}
        loading={loading}
        rowKey={rowKey}
        actionRef={actionRef}
        formRef={formRef}
        editableKeys={pageConfig?.editableKeys}
        pagination={{
          ...pagination,
          ...internalPagination,
          onChange: handlePaginationChange,
        }}
        editable={editable}
        toolBarRender={toolBarRender}
      />
    </div>
  );
};

export default PcPage;
